package cn.devcat.sso.service.impl;

import cn.devcat.sso.entity.BlogComment;
import cn.devcat.sso.mapper.BlogCommentMapper;
import cn.devcat.sso.service.IBlogCommentService;
import cn.devcat.sso.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BlogCommentServiceImpl extends ServiceImpl<BlogCommentMapper, BlogComment> implements IBlogCommentService {

  @Resource
  BlogCommentMapper commentMapper;

  @Autowired
  UserUtil userUtil;

  @Override
  public void addComment(BlogComment comment) {
    String userId = userUtil.getUserByRequest().getId();
    comment.setMainUserId(userId);
    comment.setCreateTime(LocalDateTime.now());
    if(comment.getIsMain() == null){
      comment.setIsMain(false);
    }
    save(comment);
  }

  @Override
  public void delComment(Long id) {
    String currentUserId = userUtil.getUserByRequest().getId();
    BlogComment comment = getById(id);
    if(!currentUserId.equals(comment.getMainUserId())){
      throw new RuntimeException("无法删除他人的主评论");
    }
    List<Long> ids = new ArrayList<>();
    ids.add(id);
    if(comment.getIsMain()){
      List<Long> collect = list(new QueryWrapper<BlogComment>().select("id").eq("main_comment_id", id)).stream().map(BlogComment::getId).collect(Collectors.toList());
      ids.addAll(collect);
    }
    removeByIds(ids);
  }

  @Override
  public List<BlogComment> getCommonListByNoteId(Long id) {
    List<BlogComment> list = commentMapper.getCommentListByNoteId(id);
    List<BlogComment> mainCommentList = list.stream().filter(BlogComment::getIsMain).collect(Collectors.toList());
    Map<Long, List<BlogComment>> subCommentListMap = list.stream().filter(item -> item.getMainCommentId() != null).collect(Collectors.groupingBy(BlogComment::getMainCommentId));
    for (BlogComment blogComment : mainCommentList) {
      List<BlogComment> blogComments = subCommentListMap.get(blogComment.getId());
      blogComment.setSubCommentList(blogComments);
    }
    return mainCommentList;
  }
}
